package com.example.weather.utils;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;

/**
 * Created by hanjun on 2016/6/19.
 */
public class HttpGetThread extends Thread{
    String mPath,mParam;
    Handler mHandler;
    private int messageType;

    public HttpGetThread(String path, String param, Handler handler, int messageType){
        this.mPath = path;
        this.mParam = param;
        this.mHandler = handler;
        this.messageType = messageType;
    }

    @Override
    public void run() {
        String result = null;
        //用HttpClient发送请求，分为五步
        //第一步：创建HttpClient对象
        HttpClient httpClient = new DefaultHttpClient(getParams());
        //注意，下面这一行中，我之前把链接中的"test"误写成了"text"，导致调BUG调了半天没弄出来，真是浪费时间啊

        String url;
        if(mParam ==null){
            url = mPath;
        }else{
            url = mPath+"?"+mParam;
        }
        //第二步：创建代表请求的对象,参数是访问的服务器地址
        HttpGet httpGet = new HttpGet(url);
        try {
            //第三步：执行请求，获取服务器发还的相应对象
            HttpResponse response = httpClient.execute(httpGet);
            //第四步：检查相应的状态是否正常：检查状态码的值是200表示正常
            Message message = mHandler.obtainMessage();
            if (response.getStatusLine().getStatusCode() == 200) {
                //第五步：从相应对象当中取出数据，放到entity当中
                result = NetWorkUtils.showResponseResult(response);
                Log.d("HTTP", "GET:" + result);
                message.obj = result;
            }else{
                message.obj = null;
            }
            message.what = messageType;
            mHandler.sendMessage(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private HttpParams getParams(){
        HttpParams params = new BasicHttpParams();
        //设置连接超时时间
        Integer CONNECTION_TIMEOUT = 3 * 1000; //设置请求超时3秒钟 根据业务调整
        Integer SO_TIMEOUT = 3 * 1000; //设置等待数据超时时间3秒钟 根据业务调整

        params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
        params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);
        //在提交请求之前 测试连接是否可用
        params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, true);
        return params;
    };

}
